package com.yingpai.fitness.dvp_2_0.main.activity.shop.assmble;

import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.Response;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.Utils;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.common.view.XListView;
import com.yingpai.fitness.dvp_2_0.main.bean.assmble.AssmbleDetailBean;
import com.yingpai.fitness.dvp_2_0.main.bean.assmble.AssmbleShareBean;
import com.yingpai.fitness.dvp_2_0.main.util.DialogUtil;
import com.yingpai.fitness.dvp_2_0.main.util.WXShareUtil;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.iwgang.countdownview.CountdownView;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by ASUS on 2019/1/16.
 */

public class AssmbleOrderActivity extends CommonActivity {

    @BindView(R.id.top_tv)
    TextView topTv;
    @BindView(R.id.photo)
    ImageView photo;
    @BindView(R.id.item_title)
    TextView item_title;
    @BindView(R.id.personal_count)
    TextView personalCount;
    @BindView(R.id.assmble_price)
    TextView assmblePrice;
    @BindView(R.id.common_price)
    TextView commonPrice;
    @BindView(R.id.count)
    TextView count;
    @BindView(R.id.text1)
    TextView text1;
    @BindView(R.id.text2)
    TextView text2;
    @BindView(R.id.text3)
    TextView text3;
    @BindView(R.id.time)
    CountdownView time;
    @BindView(R.id.time_ll)
    LinearLayout time_ll;
    @BindView(R.id.btn_single)
    Button btnSingle;
    @BindView(R.id.btn_double)
    LinearLayout btnDouble;
    @BindView(R.id.listview)
    XListView listview;
    @BindView(R.id.rule_tv)
    WebView rule_tv;
    @BindView(R.id.right_tv)
    TextView right_tv;
    @BindView(R.id.image_ll)
    LinearLayout image_ll;
    private AssmbleDetailBean assmbleDetailBean;
    private QuickAdapter<AssmbleDetailBean.DataBean.WowDealsBean> quickAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.activity_assmble_detail);
    }

    @Override
    protected void initView() {

        Drawable drawableLeft = getResources().getDrawable(
                R.mipmap.share);
        right_tv.setCompoundDrawablesWithIntrinsicBounds(drawableLeft,
                null, null, null);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            assmbleDetailBean = (AssmbleDetailBean) bundle.getSerializable("assmbleDetailBean");
        }

        if (assmbleDetailBean.getData().getIsHead().equals("1")) {//团长
            setTitle("开团成功");
            topTv.setText("恭喜您开团成功！");


            if(assmbleDetailBean.getData().getLack().equals("0")){
                text1.setVisibility(View.VISIBLE);
                text2.setVisibility(View.GONE);
                text3.setVisibility(View.GONE);
                text1.setText("老司机带路，马上就要发车了！");
                time_ll.setVisibility(View.GONE);
                btnDouble.setVisibility(View.GONE);
                btnSingle.setVisibility(View.VISIBLE);
                btnSingle.setText("更多拼团");
            }else{
                text1.setVisibility(View.VISIBLE);
                text2.setVisibility(View.VISIBLE);
                text3.setVisibility(View.VISIBLE);
                time_ll.setVisibility(View.VISIBLE);
                btnDouble.setVisibility(View.GONE);
                btnSingle.setVisibility(View.VISIBLE);
                btnSingle.setText("邀请好友拼团");
                text2.setText(assmbleDetailBean.getData().getLack());
                time.start(Long.parseLong((assmbleDetailBean.getData().getCountDown() == null ? "0" : assmbleDetailBean.getData().getCountDown())) * 1000);
                time.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
                    @Override
                    public void onEnd(CountdownView countdownView) {
                        showToast("该拼团已经结束");
                        finishActivity();
                        //topTv.setText("该拼团已经结束！");
                    }
                });
            }

        } else {
            setTitle("拼团成功");
            topTv.setText("恭喜您拼团成功！");
            if (assmbleDetailBean.getData().getCustomers().size() ==
                    Integer.parseInt(assmbleDetailBean.getData().getGroupBookType())) {
                btnDouble.setVisibility(View.GONE);
                btnSingle.setVisibility(View.VISIBLE);
                btnSingle.setText("更多拼团");
                time_ll.setVisibility(View.GONE);
                text1.setVisibility(View.VISIBLE);
                text2.setVisibility(View.GONE);
                text3.setVisibility(View.GONE);
                text1.setText("老司机带路，马上就要发车了！");
            } else {
                btnDouble.setVisibility(View.VISIBLE);
                btnSingle.setVisibility(View.GONE);
                time_ll.setVisibility(View.VISIBLE);
                text1.setVisibility(View.VISIBLE);
                text2.setVisibility(View.VISIBLE);
                text3.setVisibility(View.VISIBLE);
                text2.setText(assmbleDetailBean.getData().getLack());
                time.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
                    @Override
                    public void onViewAttachedToWindow(View v) {
                        time.start(Long.parseLong((assmbleDetailBean.getData().getCountDown() == null ? "0" : assmbleDetailBean.getData().getCountDown())) * 1000);
                    }

                    @Override
                    public void onViewDetachedFromWindow(View v) {
                        time.stop();
                    }
                });
                time.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
                    @Override
                    public void onEnd(CountdownView countdownView) {
                        showToast("该拼团已经结束");
                        finishActivity();
//                        topTv.setText("该拼团已经结束！");
                    }
                });
            }
        }

        Glide.with(this)
                .load(assmbleDetailBean.getData().getPhotoUrls().split(",")[0])
                .error(R.mipmap.default_small_bg)
                .into(photo);
        item_title.setText(assmbleDetailBean.getData().getMerchandiseName());
        personalCount.setText(assmbleDetailBean.getData().getGroupBookType() + "人团");
        assmblePrice.setText("￥" + assmbleDetailBean.getData().getGroupPrice());
        commonPrice.setText("￥" + assmbleDetailBean.getData().getCommonPrice());
        commonPrice.setPaintFlags(commonPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        count.setText("已拼" + assmbleDetailBean.getData().getGroupCount());
        rule_tv.loadDataWithBaseURL(null, assmbleDetailBean.getData().getGroupRule(), "text/html", "UTF-8", null);

        //应该是几人团
        image_ll.removeAllViews();//先清除它里面所有的子view

        //先获取几人团
        int anInt = Integer.parseInt(assmbleDetailBean.getData().getGroupBookType());
        //获取拼团人数
        List<AssmbleDetailBean.DataBean.CustomersBean> customers = assmbleDetailBean.getData().getCustomers();
        //把差的数组补齐
        if(anInt > customers.size()){
            int size = anInt - customers.size();
            for (int i = 0; i < size; i++) {
                AssmbleDetailBean.DataBean.CustomersBean customersBean =
                        new AssmbleDetailBean.DataBean.CustomersBean();
                customers.add(customersBean);
            }
        }
        if(customers.size() > 0){
            for (int i = 0; i < customers.size(); i++) {
                CircleImageView imageView = new CircleImageView(this);
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) imageView.getLayoutParams();
                if(layoutParams != null){
                    layoutParams.height = Utils.dipToPx(this,40);
                    layoutParams.width = Utils.dipToPx(this,40);
                }else{
                    layoutParams = new LinearLayout.LayoutParams(Utils.dipToPx(this,40),
                            Utils.dipToPx(this,40));
                }
                if(i != customers.size() -1){
                    layoutParams.setMargins(0,0,Utils.dipToPx(this,24),0);
                }

                imageView.setLayoutParams(layoutParams);
                Glide.with(this).load(customers.get(i).getPhotoUrl()).
                        error(R.mipmap.assmble_photo).
                        into(imageView);
                image_ll.addView(imageView);
            }
        }

        quickAdapter = new QuickAdapter<AssmbleDetailBean.DataBean.WowDealsBean>(this, R.layout.item_assmble_list, assmbleDetailBean.getData().getWowDeals()) {
            @Override
            protected void convert(BaseAdapterHelper helper, AssmbleDetailBean.DataBean.WowDealsBean item) {
                helper.setText(R.id.item_title, item.getMerchandiseName());
                helper.setText(R.id.personal_count, item.getGroupBookType());
                helper.setText(R.id.assmble_price, "￥" + item.getGroupPrice());
                TextView common_price = helper.getView(R.id.common_price);
                common_price.setText("￥" + item.getCommonPrice());
                common_price.setPaintFlags(common_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                helper.setText(R.id.count, "已拼" + item.getGroupCount());
                ImageView photo = helper.getView(R.id.photo);
                Glide.with(context)
                        .load(item.getPhotoUrls().split(",")[0])
                        .error(R.mipmap.default_small_bg)
                        .into(photo);
            }
        };

        listview.setAdapter(quickAdapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putString("id", quickAdapter.getItem(position).getId());
                startActivity(AssmbleShopDetailActivity.class, bundle);
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    @OnClick({R.id.btn_single, R.id.more_assmble, R.id.invite_friend, R.id.right_tv})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.btn_single:
                if (btnSingle.getText().toString().equals("邀请好友拼团")) {
                    shareAssmble();
                } else if (btnSingle.getText().toString().equals("更多拼团")) {
                    startActivity(AssmbleShopSaleActivity.class);
                }
                break;
            case R.id.more_assmble:
                startActivity(AssmbleShopSaleActivity.class);
                break;
            case R.id.invite_friend:
                shareAssmble();
                break;
            case R.id.right_tv:
                shareAssmble();
                break;
        }
    }

    private void shareAssmble() {
        showDialog(this, null);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("groupId", assmbleDetailBean.getData().getGroupBookId());
        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.ASSMBLE_SHARE, hashMap, Url.ASSMBLE_SHARE, new Callback<AssmbleShareBean>() {
            @Override
            public void onSuccess(final AssmbleShareBean assmbleShareBean) {
                dismissDialog();
                if (assmbleShareBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                    DialogUtil.getInstance().showBottomDialog(AssmbleOrderActivity.this, R.layout.dialog_invite_share);
                    LinearLayout share_dialog = (LinearLayout) DialogUtil.getInstance().dialog_bottom_layout;
                    share_dialog.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            DialogUtil.getInstance().dialog_bottom.dismiss();
                        }
                    });
                    share_dialog.findViewById(R.id.wechat_friend_share).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            DialogUtil.getInstance().dialog_bottom.dismiss();
                            WXShareUtil wxShareUtil = new WXShareUtil(AssmbleOrderActivity.this);
                            wxShareUtil.registerWx();
                            //防止取值失败
                            try {
                                wxShareUtil.share(assmbleShareBean.getData().getUrl(),
                                        assmbleShareBean.getData().getTitle(),
                                        assmbleShareBean.getData().getDescription(),
                                        assmbleShareBean.getData().getPhotoUrl(), wxShareUtil.SHARETOFRIEND);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    share_dialog.findViewById(R.id.wechat_circle_share).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            DialogUtil.getInstance().dialog_bottom.dismiss();
                            WXShareUtil wxShareUtil = new WXShareUtil(AssmbleOrderActivity.this);
                            wxShareUtil.registerWx();
                            //防止取值失败
                            try {
                                wxShareUtil.share(assmbleShareBean.getData().getUrl(),
                                        assmbleShareBean.getData().getTitle(),
                                        assmbleShareBean.getData().getDescription(),
                                        assmbleShareBean.getData().getPhotoUrl(), wxShareUtil.SHARETOPYQ);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } else {
                    showToast(assmbleShareBean.getMessage() + "");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }
}
